package com.lyl.projectspringboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyl.projectspringboot.dto.LoginDto;
import com.lyl.projectspringboot.dto.UserDto;
import com.lyl.projectspringboot.dto.UserRegisterDto;
import com.lyl.projectspringboot.dto.dtoMapper.UserMapper;
import com.lyl.projectspringboot.entity.User;
import com.lyl.projectspringboot.dao.UserDao;
import com.lyl.projectspringboot.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * @Auther 罗育良
 * @CreateDate 2025/6/8 17:44
 * @Description 这是一个关于用户的服务实现类
 */

@RequiredArgsConstructor
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    private final UserMapper userMapper;

    /**
     * @param userId
     * @return UserDto
     * @Description 根据用户UID查询用户
     */
    @Cacheable(value = "user",  key = "#userId")
    @Override
    public UserDto getUserDtoById(String userId) {
        Wrapper<User> queryWrapper = new QueryWrapper<User>()
                .select("user_id", "user_name").eq("user_id", userId);
        return userMapper.toDto(getOne(queryWrapper));
    }

    /**
     * @param userDto
     * @return boolean
     * @Description 根据用户Id更新用户
     */
    @Override
    public boolean UpdateUserById(UserDto userDto) {

        Wrapper<User> updateWrapper = new UpdateWrapper<User>()
                .eq("user_id", userDto.getUserId())
                .set("user_phone", userDto.getUserPhone())
                .set("user_name", userDto.getUserName())
                .set("user_sex", userDto.getUserSex())
                .set("user_email", userDto.getUserEmail())
                .set("user_address", userDto.getUserAddress())
                .set("user_birthday", userDto.getUserBirthday())
                .set("user_update_time", Timestamp.valueOf(LocalDateTime.now()));
        return update(updateWrapper);
    }

    /**
     * @param pageNo,pageSize
     * @return List<UserDto>
     * @Description 查询所有用户并分页且根据用户的UID进行排序
     */
    @Override
    public List<UserDto> getAllUserOrderById(Long pageNo, Long pageSize) {
        // 创建一个Page对象来表示分页查询的参数
        // 分页条件 current(当前页数pageNo),size（页面大小pageSize）
        Page<User> page = Page.of(pageNo, pageSize);
        //排序条件
        page.addOrder(new OrderItem().setAsc(true).setColumn("user_id"));
        //可以设置多个条件，但是条件顺序先添加的先执行，
        page.addOrder(new OrderItem().setAsc(true).setColumn("user_phone"));
        //接收分页结果
        Page<User> p = this.page(page);
        //解析并返回结果
        long total = p.getTotal();
        long pages = p.getPages();
        System.out.println("总页数：" + pages);
        System.out.println("总记录数：" + total);
        return userMapper.toDto(p.getRecords());

    }

    /**
     * @param loginDto
     * @return Boolean
     * @Description 用户登录, 根据用户id登录，登录成功后登录状态更新为 1
     */
    @Override
    public Boolean userLogin(LoginDto loginDto) {
        //创建查询条件
        Wrapper<User> queryWrapper = new QueryWrapper<User>()
                .eq("user_id", loginDto.getUserID())
                .eq("user_password", loginDto.getUserPWD());
        //登录成功用户状态更新为 1 （在线）
        Wrapper<User> updateWrapper = new UpdateWrapper<User>()
                .eq("user_password", loginDto.getUserPWD())
                .eq("user_id", loginDto.getUserID())
                .set("user_online_status", "1");
        //更新用户状态
        update(updateWrapper);
        //返回登录结果（查询结果）
        return getOne(queryWrapper) != null;

    }

    /**
     * @param userRegisterDto
     * @return Boolean
     * @Description 用户注册, 根据用户手机号注册，生成一个由32位的随机字符串作为用户ID，并保存到数据库中
     */
    @Override
    public Boolean UserRegister(UserRegisterDto userRegisterDto) {

        Wrapper<User> queryWrapper1 = new QueryWrapper<User>()
                .eq("user_phone", userRegisterDto.getUserPhone());
        //判断用户ID和手机号是否已存在
        User user = new User();
        if (getOne(queryWrapper1) == null) {

            while (true) {
                //生成随机字符串作为用户的初始账号Id
                String randomString = UUID.randomUUID().toString().replace("-", "");

                Wrapper<User> queryWrapper2 = new QueryWrapper<User>()
                        .eq("user_id", randomString);
                //判断生成的随机账号 Id 是否已存在，如果已存在则重新生成
                if (getOne(queryWrapper2) == null) {
                    System.out.println("生成的随机账号Id为：" + randomString);
                    //注入用户 Id 到 user 中
                    user.setUserId(randomString);
                    break;
                }
            }
            user.setUserName("用户" + user.getUserId());
            user.setUserPhone(userRegisterDto.getUserPhone());
            user.setUserPassword(userRegisterDto.getUserPWD());
            user.setUserCreationTime(Timestamp.valueOf(LocalDateTime.now()));
            user.setUserUpdateTime(Timestamp.valueOf(LocalDateTime.now()));
            return save(user);
        } else {
            return false;
        }

    }

}
